// app.js
import themeManager from "./utils/theme.js";
import storageService from "./utils/storage.js";
import apiService from "./utils/api.js";
import ConfigChecker from "./utils/config-checker.js";

App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);

    // 初始化主题
    this.initTheme();

    // 初始化用户状态
    this.initUserState();

    // 初始化API配置
    this.initApiConfig();

    // 检查项目配置
    this.checkProjectConfig();

    // 登录
    this.login();
  },

  onShow() {
    // 应用显示时的处理
    this.checkUpdate();
  },

  onHide() {
    // 应用隐藏时的处理
    this.saveAppState();
  },

  // 初始化主题
  initTheme() {
    const savedTheme = storageService.settings.getTheme();
    themeManager.setTheme(savedTheme);

    this.globalData.currentTheme = savedTheme;
    this.globalData.themeColors = themeManager.getCurrentColors();
  },

  // 初始化用户状态
  initUserState() {
    const userInfo = storageService.user.getUserInfo();
    const loginStatus = storageService.user.getLoginStatus();
    const token = storageService.user.getToken();

    this.globalData.userInfo = userInfo;
    this.globalData.isLoggedIn = loginStatus;
    this.globalData.token = token;

    // 设置API token
    if (token) {
      apiService.setToken(token);
    }
  },

  // 初始化API配置
  initApiConfig() {
    // 设置请求拦截器
    apiService.setHeaders({
      Authorization: `Bearer ${this.globalData.token}`,
    });
  },

  // 检查项目配置
  async checkProjectConfig() {
    try {
      const checkResult = await ConfigChecker.fullCheck();
      if (!checkResult.success) {
        console.warn("⚠️ 项目配置检查发现问题，请查看控制台输出");
      }
    } catch (error) {
      console.error("配置检查失败:", error);
    }
  },

  // 登录
  login() {
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log("登录成功", res);
          // 这里可以调用后端API获取用户信息
          this.handleLoginSuccess(res.code);
        } else {
          console.error("登录失败", res);
        }
      },
      fail: (err) => {
        console.error("登录失败", err);
      },
    });
  },

  // 处理登录成功
  handleLoginSuccess(code) {
    // 模拟登录成功，实际项目中应该调用后端API
    const mockUserInfo = {
      id: 1,
      nickname: "宠物爱好者",
      avatar: "/images/default-avatar.png",
      level: 1,
      points: 100,
      followCount: 50,
      fansCount: 30,
      postCount: 25,
    };

    this.setUserInfo(mockUserInfo);
    this.setLoginStatus(true);
  },

  // 设置用户信息
  setUserInfo(userInfo) {
    this.globalData.userInfo = userInfo;
    storageService.user.setUserInfo(userInfo);
  },

  // 设置登录状态
  setLoginStatus(status) {
    this.globalData.isLoggedIn = status;
    storageService.user.setLoginStatus(status);
  },

  // 设置token
  setToken(token) {
    this.globalData.token = token;
    storageService.user.setToken(token);
    apiService.setToken(token);
  },

  // 退出登录
  logout() {
    this.globalData.userInfo = null;
    this.globalData.isLoggedIn = false;
    this.globalData.token = "";

    storageService.user.clearUserData();
    apiService.clearToken();
  },

  // 检查更新
  checkUpdate() {
    if (wx.canIUse("getUpdateManager")) {
      const updateManager = wx.getUpdateManager();

      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: "更新提示",
              content: "新版本已经准备好，是否重启应用？",
              success: (res) => {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              },
            });
          });
        }
      });
    }
  },

  // 保存应用状态
  saveAppState() {
    // 保存当前应用状态到本地存储
    const appState = {
      timestamp: Date.now(),
      currentPage: this.globalData.currentPage,
      theme: this.globalData.currentTheme,
    };

    storageService.set("appState", appState);
  },

  // 显示加载提示
  showLoading(title = "加载中...") {
    wx.showLoading({
      title,
      mask: true,
    });
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },

  // 显示提示信息
  showToast(title, icon = "none", duration = 2000) {
    wx.showToast({
      title,
      icon,
      duration,
    });
  },

  // 显示模态框
  showModal(title, content, showCancel = true) {
    return new Promise((resolve) => {
      wx.showModal({
        title,
        content,
        showCancel,
        success: (res) => {
          resolve(res.confirm);
        },
      });
    });
  },

  // 获取系统信息
  getSystemInfo() {
    return new Promise((resolve) => {
      wx.getSystemInfo({
        success: resolve,
        fail: () => resolve(null),
      });
    });
  },

  // 获取网络状态
  getNetworkType() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success: (res) => resolve(res.networkType),
        fail: () => resolve("unknown"),
      });
    });
  },

  globalData: {
    userInfo: null,
    isLoggedIn: false,
    token: "",
    currentTheme: "light",
    themeColors: {},
    currentPage: "",
    systemInfo: null,
    networkType: "wifi",
  },
});
